<template>
  <view class="pages">
    <u-sticky class="sticky_c" offsetTop="0" :style="{ backgroundColor: scrollBgc ? '#fff' : '#fff' }">
      <h-line :height="statusHeight + 20"></h-line>
      <view class="navbar">
        <view class="nav_b">
          <u-icon name="arrow-left" size="22" color="#333" @click="goBack"></u-icon>
        </view>
        <view class="page_title">睡眠记录</view>
        <view class="nav_right">
          <view v-if="isShowBtn && sleepRecordList.length" class="right_item" @click="toShare">
            <image src="@/static/imgs/share_icon.png" mode="scaleToFill" />
          </view>
          <view v-else class="right_item" style="width: 40rpx"></view>
        </view>
      </view>
    </u-sticky>
    <view class="calendar">
      <zeng-calen :legend="legendList" :endTime="endDate" :chooseDay="chooseDay" :isMsgInfo="isMsgInfo"
        :isCurrentDay="isCurrentDay" :startTime="zengStartDate" @onBacktoday="onBacktoday" @onDayClick="onDayClick"
        @onMonthChange="onMonthChange" lightBgColoor="#fff" textColor="#54CEAB" backtodayText="返回今天"
        backBgColor="#B1EEDC"></zeng-calen>
    </view>
    <view style="width: 702rpx; margin: 20rpx auto">
      <h-slideDelete :isShowEitn="isShowBtn" :itemList="sleepRecordList" :isTouch="isTouch" backgroundItem="#fff"
        @deleteItem="deleteList" @eidtSleep="eidtSleep"></h-slideDelete>
    </view>
    <!-- <view v-if="isShowBtn" style="margin-bottom: 40rpx">
      <view class="no_records_box" v-if="isNocturnalSleep">
        <view class="night_sleep" @click="nocturnalSleep">记录夜间睡眠</view>
        <view class="rest_record" @click="restRecord">记录小憩</view>
      </view>
      <view v-else class="">
        <view class="rest_record" @click="restRecord">记录小憩</view>
      </view>
    </view> -->
  </view>
  <h-modal :show="bindShow" titlea="确认删除这条记录吗？" leftBtn="取消" btnColor="#2ABE93" rightBtn="确认" @clear="clearEdit"
    @bind="saveEditFn"></h-modal>
  <!-- 睡眠管理管理弹窗 -->
  <u-popup :show="showSleep" :round="10" mode="bottom" @close="showSleep = false">
    <view class="sleep_pop_box">
      <view class="sleep_pop_title">
        <view v-if="!isRestBind" class="title_text">选择睡眠时间</view>
        <view v-else class="title_text">选择小憩时间</view>
        <view class="pop_close" @click="sLeepPopClose">
          <up-icon name="close" color="#333333" size="20"></up-icon>
        </view>
      </view>
      <view class="fall_asleep">
        <view>
          <text>入睡时间</text>
          <text v-if="!isRestBind" style="margin-left: 20rpx; color: #666666">昨天</text>
          <text v-else style="margin-left: 20rpx; color: #666666">今天</text>
        </view>
        <view class="dateTime_box">
          <h-sleep-dateTime @timeChange="sleepStartTimeChange" :startTime='startTimeE'></h-sleep-dateTime>
        </view>
      </view>
      <view class="fall_asleep">
        <view>
          <text>起床时间</text>
          <text style="margin-left: 20rpx; color: #666666">今天</text>
        </view>
        <view class="dateTime_box">
          <h-sleep-dateTime @timeChange="sleepEndTimeChange" :endTime="endTimeE"></h-sleep-dateTime>
        </view>
      </view>
      <view class="sleep_time_save" @click="sleepTimeSave">保存</view>
    </view>
  </u-popup>
  <h-share ref="shareRef" :showLh="false" :isDoctor="true" servicesType="3" @gotoChat="gotoChatShare"></h-share>
  <h-login ref="login"></h-login>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { navigateBack, navigateTo, formatDate, showToast } from '@/utils'
import { onLoad, onPageScroll, onShow } from '@dcloudio/uni-app'
import { useMemberStore } from '@/stores'
import {
  getSleepDateRecord,
  editSleepDateRecord,
  addRecordSleep,
  delSleepRecord,
  getSleepDateList,
  getRecordStartDate,
} from '@/api/pregnancy/index'

const login = ref(null) // 登录组件实例
const store = useMemberStore()
const shareRef = ref(null)
const scrollBgc = ref(false)
const statusHeight = ref()
const bindShow = ref(false)
const isNocturnalSleep = ref(true)
//是否聊天过来
const isShowBtn = ref(false)
//编辑睡眠
const showSleep = ref(false)
const isRestBind = ref(false)
//睡眠记录列表
const sleepRecordList = ref([])
//用户选择的日期
const chooseDay = ref([])

// 日历截止时间
const endDate = ref(formatDate(Date.now(), 'YYYY-MM-DD'))

const legendList = ref([
  {
    icon: 'https://ossresource.miyingbl.com/uploads/20240509/102710906766443a89afa52ff3e6ba23.png',
    name: '夜间睡眠',
  },
  {
    icon: 'https://ossresource.miyingbl.com/uploads/20240509/377b85eaf409fb8b95b98af09f00cb52.png',
    name: '小憩',
  },
])
const isMsgInfo = ref(true)
const isCurrentDay = ref(false)
const isTouch = ref(false)
const userId = ref(0)
onLoad((options) => {
  userId.value = options?.userId
  sleepPreams.value.uid = options?.userId
  sleepRecordPreams.value.uid = options?.userId
  // if (options.isshow === false || options.isshow == 'false') {
  //   isShowBtn.value = false
  //   isTouch.value = false
  // } else {
  //   isShowBtn.value = true
  //   isTouch.value = true
  // }
  if (options?.day && options?.time) {
    sleepRecordPreams.value.child_id = options?.childId
    sleepRecordPreams.value.date = options.time

    getSleepDateRecordFn()
    if (options.time == formatDate(new Date(), 'YYYY-MM-DD')) {
      isMsgInfo.value = true
      isCurrentDay.value = false
    } else {
      isMsgInfo.value = false
      isCurrentDay.value = true
    }
    let today = new Date(options.time)
    today.setDate(today.getDate() - options.day + 1)
    zengStartDate.value = formatDate(today, 'YYYY-MM-DD')
    endDate.value = formatDate(new Date(options.time), 'YYYY-MM-DD')
  } else {
    startParams.value.uid = options?.userId
    startParams.value.child_id = options?.childId
    getRecordStartDateFn()
  }
  var year = formatDate(new Date(), 'YYYY')
  var month = formatDate(new Date(), 'MM')
  var day = formatDate(new Date(year, month, 0), 'DD')
  dateListPreams.value.start_date = year + '-' + month + '-01'
  dateListPreams.value.uid = options?.userId
  dateListPreams.value.end_date = year + '-' + month + '-' + day
  dateListPreams.value.child_id = options?.childId
  sleepRecordPreams.value.child_id = options?.childId
  getSleepDateListFn()
})
onShow(() => {
  uni.getSystemInfo({
    success: (e) => {
      statusHeight.value = e?.statusBarHeight * 2
    },
  })
  getSleepDateRecordFn()
})
//返回
function goBack() {
  navigateBack()
}
//删除开始
const itemRecordId = ref(0)
const itemRecordIndex = ref(0)
const itemRecordType = ref(0)
function deleteList(id, type, index) {
  bindShow.value = true
  itemRecordId.value = id
  itemRecordIndex.value = index
  itemRecordType.value = type
}
function clearEdit() {
  bindShow.value = false
}
//确认删除
function saveEditFn() {
  delSleepRecordFn()
}
//编辑睡眠
const iseidtFlag = ref(false)
const startTimeE = ref('')
const endTimeE = ref('')
function eidtSleep(id, type, startTime, endTime) {
  startTimeE.value = startTime
  endTimeE.value = endTime
  iseidtFlag.value = true
  sleepPreams.value.id = id
  sleepPreams.value.type = type
  if (type == 1) {
    isRestBind.value = false
  } else {
    isRestBind.value = true
  }
  showSleep.value = true
}
//睡眠时间选择参数
const sleepPreams = ref({
  date: '',
  start_time: '',
  end_time: '',
  type: 1,
  form: 3,
  child_id: 0,
  uid:0
})
//睡眠开始时间
function sleepStartTimeChange(e) {
  let todayDate = new Date(sleepRecordPreams.value.date)
  let currentDate = new Date(sleepRecordPreams.value.date)
  currentDate.setDate(currentDate.getDate() - 1)
  if (sleepPreams.value.type == 1) {
    sleepPreams.value.start_time = `${formatDate(currentDate, 'YYYY-MM-DD')} ${e}:00`
  } else {
    sleepPreams.value.start_time = `${formatDate(todayDate, 'YYYY-MM-DD')} ${e}:00`
  }
}
//结束
function sleepEndTimeChange(e) {
  let todayDate = new Date(sleepRecordPreams.value.date)
  sleepPreams.value.end_time = `${formatDate(todayDate, 'YYYY-MM-DD')} ${e}:00`
}
//睡眠保存
function sleepTimeSave() {
  if (iseidtFlag.value == true) {
    sleepPreams.value.date = sleepRecordPreams.value.date
    if (!sleepPreams.value.start_time || !sleepPreams.value.end_time) {
      showToast('请编辑睡眠时间')
    } else {
      if (sleepPreams.value.start_time == sleepPreams.value.end_time) {
        showToast('起床时间应大于睡眠时间')
      } else {
        editSleepDateRecordFn()
      }
    }
  } else {
    sleepPreams.value.date = sleepRecordPreams.value.date
    if (!sleepPreams.value.start_time || !sleepPreams.value.end_time) {
      showToast('请选择睡眠时间')
    } else {
      if (sleepPreams.value.start_time == sleepPreams.value.end_time) {
        showToast('起床时间应大于睡眠时间')
      } else {
        addRecordSleepFn()
      }
    }
  }
}
function sLeepPopClose() {
  showSleep.value = false
}

// 切换日期
const onDayClick = (e) => {
  sleepRecordPreams.value.date = e.date
  getSleepDateRecordFn()
  console.log(sleepRecordList.value)
}
// 切换月份
const onMonthChange = (e) => {
  let year = e.momth.slice(0, 4)
  let month = ''
  if (e.momth.slice(-2) < 0) {
    month = `0${e.momth.slice(-1)}`
  } else {
    month = e.momth.slice(-2)
  }
  var day = formatDate(new Date(year, month, 0), 'DD')
  dateListPreams.value.start_date = year + '-' + month + '-01'
  dateListPreams.value.end_date = year + '-' + month + '-' + day
  getSleepDateListFn()
}

const restRecord = () => {
  startTimeE.value = ''
  endTimeE.value = ''
  showSleep.value = true
  isRestBind.value = true
  iseidtFlag.value = false
  sleepPreams.value.type = 2
}

const nocturnalSleep = () => {
  startTimeE.value = ''
  endTimeE.value = ''
  showSleep.value = true
  isRestBind.value = false
  iseidtFlag.value = false
  sleepPreams.value.type = 1
}
//回今天
function onBacktoday() {
  sleepRecordPreams.value.date = formatDate(new Date(), 'YYYY-MM-DD')
  getSleepDateRecordFn()
  let year = formatDate(new Date(), 'YYYY')
  let month = formatDate(new Date(), 'MM')
  var day = formatDate(new Date(year, month, 0), 'DD')
  dateListPreams.value.start_date = year + '-' + month + '-01'
  dateListPreams.value.end_date = year + '-' + month + '-' + day
  getSleepDateListFn()
}
//获取睡眠记录
const sleepRecordPreams = ref({
  date: formatDate(new Date(), 'YYYY-MM-DD'),
  form: 3,
  child_id: 0,
  uid:0
})
async function getSleepDateRecordFn() {
  const res = await getSleepDateRecord(sleepRecordPreams.value)
  if (res?.code == 200) {
    if (res.data.data.length > 0) {
      res.data.data.map((item) => {
        let index = item.start_time.indexOf(' ')
        if (index !== -1 && index + 6 <= item.start_time.length) {
          item.start_time = item.start_time.slice(index + 1, index + 6)
          item.end_time = item.end_time.slice(index + 1, index + 6)
        }
      })
      let indexType = res.data.data.findIndex((v) => v.type == 1)
      if (indexType !== -1) {
        isNocturnalSleep.value = false
      } else {
        isNocturnalSleep.value = true
      }
      sleepRecordList.value = res.data.data
    } else {
      isNocturnalSleep.value = true
      sleepRecordList.value = []
    }
  } else {
    showToast(res.msg)
  }
}
//编辑
async function editSleepDateRecordFn() {
  const res = await editSleepDateRecord(sleepPreams.value)
  if (res?.code == 200) {
    sleepPreams.value.start_time = ''
    sleepPreams.value.end_time = ''
    showToast(res.msg)
    getSleepDateRecordFn()
    showSleep.value = false
  } else {
    showToast(res.msg)
    if (res.msg == '缺少参数') {
      showToast('请选择睡眠时间')
    }
  }
}
//添加睡眠时间
async function addRecordSleepFn() {
  const res = await addRecordSleep(sleepPreams.value)
  if (res?.code == 200) {
    sleepPreams.value.start_time = ''
    sleepPreams.value.end_time = ''
    showToast(res.msg)
    showSleep.value = false
    getSleepDateRecordFn()
    getSleepDateListFn()
  } else {
    showToast(res.msg)
    if (res.msg == '缺少参数') {
      showToast('请选择睡眠时间')
    }
  }
}

//删除睡眠记录
async function delSleepRecordFn() {
  const res = await delSleepRecord({ id: itemRecordId.value })
  if (res?.code == 200) {
    // if (itemRecordType.value == 1) {
    //   isNocturnalSleep.value = true
    // } else {
    //   isNocturnalSleep.value = false
    // }
    showToast(res.msg)
    bindShow.value = false
    sleepRecordList.value.splice(itemRecordIndex.value, 1)

    getSleepDateRecordFn()
    getSleepDateListFn()
  } else {
    showToast(res.msg)
  }
}
//获取日期记录
const dateListPreams = ref({
  start_date: '',
  end_date: '',
  form: 3,
  child_id: 0,
  uid:0
})
async function getSleepDateListFn() {
  const res = await getSleepDateList(dateListPreams.value)
  if (res?.code == 200) {
    chooseDay.value = res.data.data
  } else {
    showToast(res.msg)
  }
}
// 获取用户记录的第一天的日期
const startParams = ref({
  uid: 0,
  form: 3,
  child_id: 0
})
const zengStartDate = ref('')
const zengEndDate = ref('')
async function getRecordStartDateFn() {
  sleepPreams.value.child_id = startParams.value.child_id
  const res = await getRecordStartDate(startParams.value)
  if (res?.code == 200) {
    console.log(res)
    let date = new Date(res.data.date)
    var firstDayOfYear = new Date(date.getFullYear(), 0, 1)
    var lastDayOfYear = new Date(date.getFullYear(), 11, 31)
    zengStartDate.value = formattedDate(firstDayOfYear)
    zengEndDate.value = formattedDate(lastDayOfYear)
  } else {
    showToast(res.msg)
  }
}
function formattedDate(date1) {
  var date2 = new Date(date1)
  var year = date2.getFullYear()
  var month = ('0' + (date2.getMonth() + 1)).slice(-2)
  var day = ('0' + date2.getDate()).slice(-2)
  var formattedDate = year + '-' + month + '-' + day
  return formattedDate
}
//分享
function toShare() {
  if (store.token) {
    shareRef.value.open()
  } else {
    login.value.open()
  }
}
//分享到医生
function gotoChatShare(i) {
  console.log(i)
  if (sleepRecordList.value.length > 0) {
    uni.navigateTo({
      url: `/pregnancy/index/doctor-chat?chatData=${encodeURIComponent(
        JSON.stringify({
          doctor_id: i?.doctor_id,
          avatar: i?.avatar,
          name: i?.name,
          id: i?.id,
          gradualchange: '#A7E4D4',
          chattype: 3,
          buttonColor: '#54CEAB',
          color: '#54CEAB',
          background: '#fff',
          date: sleepRecordPreams.value.date
        }),
      )}`,
    })
    // navigateTo(
    //   `/pregnancy/index/doctor-chat?type=1&doctor_id=${i?.doctor_id}&avatar=${i?.avatar}&name=${i?.dname}&id=${i?.id}&date=${sleepRecordPreams.value.date}`,
    // )
  } else {
    showToast('当前日期没有记录')
  }
}
</script>

<style lang="scss" scoped>
.pages {
  min-height: 100vh;
  background: #F6F6F6;
  font-family: PingFang SC, PingFang SC;
  display: flex;
  flex-direction: column;
  align-items: center;

  .no_records_box {
    width: 530rpx;
    margin: 40rpx auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .records_box {
    width: 530rpx;
    margin: 40rpx auto;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.calendar {
  background: #fff;
  padding-bottom: 48rpx;
  width: 750rpx;
}

.rest_record,
.night_sleep {
  width: 227rpx;
  height: 68rpx;
  background: #54CEAB;
  border-radius: 91rpx 91rpx 91rpx 91rpx;
  font-weight: 600;
  font-size: 28rpx;
  color: #ffffff;
  text-align: center;
  line-height: 68rpx;
}

.sticky_c {
  top: 0 !important;

  // background: url('@/static/imgs/time_table_bg.png') no-repeat;
  // background-size: 100%;
  .navbar {
    padding: 0 24rpx;
    width: 100vw;
    height: 100rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    box-sizing: border-box;

    .page_title {
      font-family: PingFang SC, PingFang SC;
      font-weight: 600;
      font-size: 36rpx;
      color: #333333;
      margin-left: 11rpx;
      margin-right: 20rpx;
      line-height: 100rpx;
      text-align: center;
      flex: 1;
    }

    .nav_b {
      width: 100rpx;
      height: 32rpx;
      padding: 30rpx 0;
    }

    .nav_right {
      display: flex;
      align-items: center;

      .right_item {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-left: 56rpx;

        image {
          width: 35rpx;
          height: 35rpx;
          margin-bottom: 4rpx;
        }
      }
    }
  }
}

//睡眠弹窗
.sleep_pop_box {
  width: 700rpx;
  margin: 0 auto;

  .sleep_pop_title {
    margin-top: 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-left: 24rpx;

    .title_text {
      font-weight: 600;
      font-size: 28rpx;
      color: #333333;
      margin: 0 auto;
    }

    .pop_close {
      width: 42rpx;
      height: 42rpx;
      background: #f2f2f2;
      border-radius: 6rpx 6rpx 6rpx 6rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .fall_asleep {
    padding: 0 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 20rpx 0;

    .dateTime_box {
      width: 241rpx;
    }

    text {
      font-size: 28rpx;
      color: #333333;
    }
  }

  .sleep_time_save {
    margin: 30rpx auto;
    width: 702rpx;
    height: 88rpx;
    background: #54CEAB;
    border-radius: 91rpx 91rpx 91rpx 91rpx;
    font-weight: 600;
    font-size: 32rpx;
    color: #ffffff;
    text-align: center;
    line-height: 88rpx;
  }
}
</style>
